﻿using System;
using System.Management;

namespace Nextensions.Administration
{
    public static class IP
    {
        public static void SetStaticIp(string[] Ip, string[] SubNet, string Gateway, string[] Dns)
        {
            ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'");
            ManagementObjectCollection configInstances = query.Get();

            foreach (ManagementObject adapterConfig in configInstances)
            {
                ManagementBaseObject newIp = null;
                ManagementBaseObject setIp = null;
                ManagementBaseObject gateway = null;
                ManagementBaseObject dns = null;

                newIp = adapterConfig.GetMethodParameters("EnableStatic");
                gateway = adapterConfig.GetMethodParameters("SetGateways");
                dns = adapterConfig.GetMethodParameters("SetDNSServerSearchOrder");

                //Set DefaultGateway
                gateway["DefaultIPGateway"] = new string[] { Gateway };
                //gateway["GatewayCostMetric"] = new int[] { 1 };

                // Usually you want te same subnet for all the IPs...
                if (SubNet.Length != Ip.Length && SubNet.Length == 1)
                {
                    string[] temp = SubNet;

                    SubNet = new string[Ip.Length];

                    for (int i = 0; i < Ip.Length; i++)
                        SubNet[i] = temp[0];
                }

                //Set IPAddress and Subnet Mask
                newIp["IPAddress"] = Ip;
                newIp["SubnetMask"] = SubNet;

                dns["DNSServerSearchOrder"] = Dns;

                adapterConfig.InvokeMethod("EnableStatic", newIp, null);
                setIp = adapterConfig.InvokeMethod("SetGateways", gateway, null);
                adapterConfig.InvokeMethod("SetDNSServerSearchOrder", dns, null);
                break;
            }
        }
    }
}
